﻿using System;
using System.Collections.Generic;
using System.Data.Linq.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CheckNameProject
{
    public partial class _Default : System.Web.UI.Page
    {
        public static string path="";
        DBNameCheckDataContext db = new DBNameCheckDataContext();

        protected void Page_Load(object sender, EventArgs e)
        {
            txtAddDate.Attributes.Add("onkeypress", "return NoPush();");
            txtBeginDate.Attributes.Add("onkeypress", "return NoPush();");
            txtFinishDate.Attributes.Add("onkeypress", "return NoPush();");
            
            if (!Page.IsPostBack)
            {
                panAddDoc.Visible = false;
                gvDoc.DataSource = SqlDataSource1;
                gvDoc.DataBind();

                var q = (from p in db.Documents
                        where p.StatusID == 0
                        select p).Count();
                lblCount.Text = q.ToString();
            }
        }

        protected void btnAddDoc_Click(object sender, EventArgs e)
        {
            panAddDoc.Visible = true;
            panBtnAdd.Visible = false;
        }

        protected void btnConfirmDoc_Click(object sender, EventArgs e)
        {
            DBNameCheckDataContext db = new DBNameCheckDataContext();
            Document Doc = new Document();

            if (FileUploadControl.HasFile)
            {
                if (FileUploadControl.PostedFile.ContentType == "application/pdf")
                {
                    string filename = txtAddDocName.Text + ".pdf";
                    FileUploadControl.SaveAs(Server.MapPath("~/Document/") + filename);
                    path = Server.MapPath("~/Document/") + filename;
                    //lblStatUpload.ForeColor = System.Drawing.Color.Blue;
                    //lblStatUpload.Text = "อัพโหลดเสร็จเรียบร้อย";
                    //btnUpload.Enabled = false;

                    Doc.DateUpload = DateTime.Now;
                    Doc.DocumentName = txtAddDocName.Text;
                    Doc.StatusID = 0;
                    Doc.Date = Convert.ToDateTime(txtAddDate.Text, new CultureInfo("en-GB"));
                    Doc.Path = path;
                    db.Documents.InsertOnSubmit(Doc);
                    db.SubmitChanges();

                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    //lblStatUpload.ForeColor = System.Drawing.Color.Red;
                    //lblStatUpload.Text = "กรุณาเลือกเฉพาะไฟล์ PDF เท่านั้น!!!";
                    StringBuilder sb = new StringBuilder();
                    sb = new StringBuilder();
                    sb.Append("<script language='javascript' type='text/javascript'>");
                    sb.Append("alert('กรุณาเลือกเฉพาะไฟล์ PDF เท่านั้น!!!')");
                    sb.Append("</script>");
                    Response.Write(sb.ToString());
                }
            }
            else
            {
                Doc.DateUpload = DateTime.Now;
                Doc.DocumentName = txtAddDocName.Text;
                Doc.StatusID = 0;
                Doc.Date = DateTime.Parse(txtAddDate.Text, new CultureInfo("en-GB"));
                db.Documents.InsertOnSubmit(Doc);
                db.SubmitChanges();

                Response.Redirect("~/Default.aspx");
            }
        }

        protected void btnCancelDoc_Click(object sender, EventArgs e)
        {
            if (path!="")
            {
               File.Delete(path);
            }
            Response.Redirect("~/Default.aspx");
        }

        protected void cbSort_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbSort.SelectedIndex == 0)
            {
                gvDoc.DataSource = SqlDataSource1;
                gvDoc.DataBind();
            }
            if (cbSort.SelectedIndex == 1)
            {
                gvDoc.DataSource = SqlDocIncomplete;
                gvDoc.DataBind();
            }
            if (cbSort.SelectedIndex == 2)
            {
                gvDoc.DataSource = SqlDocComplete;
                gvDoc.DataBind();
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            DBNameCheckDataContext db = new DBNameCheckDataContext();

            if (!txtDocName.Text.Equals(""))
            {
                
                var q = from p in db.Documents
                        where p.DocumentName.Contains(txtDocName.Text)
                        orderby p.Date descending
                        select new {p.DocumentID,p.DocumentName,p.Path,p.Date,p.DateUpload,p.StatusID};

                gvDoc.DataSource = q.ToList();
                gvDoc.DataBind();
               
            }
            else if (!txtBeginDate.Text.Equals("") && !txtFinishDate.Text.Equals(""))
            {
                if (Convert.ToDateTime(txtBeginDate.Text, new CultureInfo("en-GB")) >= Convert.ToDateTime(txtFinishDate.Text, new CultureInfo("en-GB")))
                {
                    StringBuilder sb = new StringBuilder();
                    sb = new StringBuilder();
                    sb.Append("<script language='javascript' type='text/javascript'>");
                    sb.Append("alert('วันที่ไม่ถูกต้อง!!!')");
                    sb.Append("</script>");
                    Response.Write(sb.ToString());
                }
                else
                {
                    var q = from p in db.Documents
                            where p.Date > Convert.ToDateTime(txtBeginDate.Text, new CultureInfo("en-GB")) &&
                            p.Date < Convert.ToDateTime(txtFinishDate.Text, new CultureInfo("en-GB"))
                            orderby p.Date descending
                            select p;
                    gvDoc.DataSource = q.ToList();
                    gvDoc.DataBind();
                    
                }
            }
            else
            {
                gvDoc.DataSource = SqlDataSource1;
                gvDoc.DataBind();
            }

            txtDocName.Text = "";
            txtBeginDate.Text = "";
            txtFinishDate.Text = "";
        }

        protected void gvDoc_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvDoc.PageIndex = e.NewPageIndex;
            gvDoc.DataSource = SqlDataSource1;
            gvDoc.DataBind();
        }

        protected void gvDoc_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            HiddenField HD = (HiddenField)(gvDoc.Rows[e.RowIndex].FindControl("HiddenField1"));
            int ID = int.Parse(HD.Value);
            var qMain = from p in db.Documents
                    where p.DocumentID == ID
                    select p;

            db.Documents.DeleteAllOnSubmit(qMain.ToList());

            var qSub = from p in db.Status
                    where p.DocumentID == ID
                    select p;

            db.Status.DeleteAllOnSubmit(qSub.ToList());

            //Delete File
            var qFile = (from p in db.Documents
                         where p.DocumentID == ID
                         select p).Single();
            if (qFile.Path != null)
            {
                try
                {
                    File.Delete(qFile.Path);
                }
                catch (Exception)
                {
                }
                
            }

            db.SubmitChanges();
            Response.Redirect("~/Default.aspx");
            
        }

        protected void gvDoc_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            ImageButton lnkDelete = (ImageButton)(e.Row.FindControl("ImageButton1"));

            if (lnkDelete != null)
            {
                lnkDelete.Attributes.Add("OnClick", "return confirm('Delete Record?');");
            }
        }
    }
}
